// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.NavAfterSellOrder;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.inventory.model.InventoryOutboundVo;
import com.fowo.api.inventory.model.PatternEnum;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryOutboundFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.NavAfterSellOrderDetailMapper;
import com.fowo.api.mapper.NavAfterSellOrderMapper;
import com.fowo.api.mapper.NavLogisticsChannelViewMapper;
import com.fowo.api.mapper.NavLogisticsProviderViewMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.SysCountryMapper;
import com.fowo.api.mapper.SysRegionMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.nav.after.sell.order.NavAfterSellOrderCancelAction;
import com.fowo.api.model.nav.after.sell.order.NavAfterSellOrderExcelPo;
import com.fowo.api.model.nav.after.sell.order.NavAfterSellOrderImportPo;
import com.fowo.api.model.nav.after.sell.order.NavAfterSellOrderIssuRefundAction;
import com.fowo.api.model.nav.after.sell.order.NavAfterSellOrderIssuReturnAction;
import com.fowo.api.model.nav.after.sell.order.NavAfterSellOrderItemVo;
import com.fowo.api.model.nav.after.sell.order.NavAfterSellOrderProcessAction;
import com.fowo.api.model.nav.after.sell.order.NavAfterSellOrderSearchParamPo;
import com.fowo.api.model.nav.after.sell.order.NavAfterSellOrderSubmitAction;
import com.fowo.api.model.nav.after.sell.order.NavAfterSellOrderVo;
import com.fowo.api.model.nav.after.sell.order.detail.NavAfterSellOrderDetailItemVo;
import com.fowo.api.model.nav.after.sell.order.detail.NavAfterSellOrderDetailSearchParamPo;
import com.fowo.api.model.nav.logistics.channel.view.NavLogisticsChannelViewItemVo;
import com.fowo.api.model.nav.logistics.channel.view.NavLogisticsChannelViewSearchParamPo;
import com.fowo.api.model.nav.logistics.provider.view.NavLogisticsProviderViewItemVo;
import com.fowo.api.model.nav.logistics.provider.view.NavLogisticsProviderViewSearchParamPo;
import com.fowo.api.model.nav.sell.order.declare.NavSellOrderDeclareSearchParamPo;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailSearchParamPo;
import com.fowo.api.model.nav.sell.order.platform.NavSellOrderPlatformSearchParamPo;
import com.fowo.api.model.nav.sell.order.transaction.NavSellOrderTransactionSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.sys.country.SysCountryItemVo;
import com.fowo.api.model.sys.country.SysCountrySearchParamPo;
import com.fowo.api.model.sys.region.SysRegionItemVo;
import com.fowo.api.model.sys.region.SysRegionSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.NavAfterSellOrderDetailService;
import com.fowo.api.service.NavAfterSellOrderService;
import com.fowo.api.service.NavSellOrderDeclareService;
import com.fowo.api.service.NavSellOrderDetailService;
import com.fowo.api.service.NavSellOrderPlatformService;
import com.fowo.api.service.NavSellOrderTransactionService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.sys.ssf.SimpleStatusFlowService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 订单管理售后工单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：任凯，沈友谅
 */
@Slf4j
@DataObjectType(NavAfterSellOrder.class)
@DS("ds24")
public class NavAfterSellOrderBaseServiceImpl
  extends ServiceImpl<NavAfterSellOrderMapper, NavAfterSellOrder>
  implements NavAfterSellOrderService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("shopInfoShopName", "si.`shop_name`");
      put("siteName", "sr.`name`");
      put("deliveryLogisticsLabel", "nlpv.`label`");
      put("deliveryCountryCountry", "sc.`country`");
      put("deliveryWarehouseName", "w.`name`");
      put("deliveryLogisticsChannelLabel", "nlcv.`label`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected NavAfterSellOrderService self;

  @Resource
  protected NavAfterSellOrderDetailService navAfterSellOrderDetailService;

  @Resource
  protected NavSellOrderPlatformService navSellOrderPlatformService;

  @Resource
  protected NavSellOrderTransactionService navSellOrderTransactionService;

  @Resource
  protected NavSellOrderDetailService navSellOrderDetailService;

  @Resource
  protected NavSellOrderDeclareService navSellOrderDeclareService;

  @Resource
  protected SimpleStatusFlowService simpleStatusService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected SysRegionMapper sysRegionMapper;

  @Resource
  protected NavLogisticsProviderViewMapper navLogisticsProviderViewMapper;

  @Resource
  protected SysCountryMapper sysCountryMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected NavLogisticsChannelViewMapper navLogisticsChannelViewMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected NavAfterSellOrderSubmitAction navAfterSellOrderSubmitAction;

  @Autowired(required = false)
  protected NavAfterSellOrderProcessAction navAfterSellOrderProcessAction;

  @Autowired(required = false)
  protected NavAfterSellOrderCancelAction navAfterSellOrderCancelAction;

  @Autowired(required = false)
  protected NavAfterSellOrderIssuRefundAction navAfterSellOrderIssuRefundAction;

  @Autowired(required = false)
  protected NavAfterSellOrderIssuReturnAction navAfterSellOrderIssuReturnAction;

  @Resource
  protected InventoryBusinessService inventoryBusinessService;

  @Resource
  protected Validator validator;

  /**
   * 创建订单管理售后工单
   * @param model 订单管理售后工单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(NavAfterSellOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    NavAfterSellOrder entity = new NavAfterSellOrder();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getWay() == null) {
      entity.setWay("1");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getAfterId())) {
      entity.setAfterId(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "NavAfterSellOrder.afterId")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      simpleStatusService.afterCreate(
        "NavAfterSellOrder",
        currentUser == null ? "" : currentUser.getDisplayName(),
        entity.getId(),
        entity.getStatus()
      );
      return entity.getId();
    }
    throw new Exception("订单管理售后工单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 订单管理售后工单
   */
  protected void updateAllChilds(NavAfterSellOrderVo model) throws Exception {
    if (model.getDetail() != null) {
      navAfterSellOrderDetailService.saveAllByParentNavAfterSellOrder(
        model.getId(),
        model.getDetail()
      );
    }

    if (model.getPlatform() != null) {
      navSellOrderPlatformService.saveAllByNavAfterSellOrderPlatform(
        model,
        model.getPlatform()
      );
    }

    if (model.getTransaction() != null) {
      navSellOrderTransactionService.saveAllByNavAfterSellOrderTransaction(
        model,
        model.getTransaction()
      );
    }

    if (model.getProduct() != null) {
      navSellOrderDetailService.saveAllByNavAfterSellOrderProduct(
        model,
        model.getProduct()
      );
    }

    if (model.getDeclare() != null) {
      navSellOrderDeclareService.saveAllByNavAfterSellOrderDeclare(
        model,
        model.getDeclare()
      );
    }
  }

  /**
   * 更新订单管理售后工单
   * @param model 订单管理售后工单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(NavAfterSellOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    NavAfterSellOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("订单管理售后工单不存在");
    }
    // 获取简单状态
    String rawSimpleStatus = entity.getStatus();
    BeanUtils.copyProperties(
      model,
      entity,
      "afterId",
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "platform",
      "transaction",
      "product",
      "declare"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      // 简单流程状态更新
      if (model.getStatus() != null) {
        simpleStatusService.afterUpdate(
          "NavAfterSellOrder",
          currentUser == null ? "" : currentUser.getDisplayName(),
          entity.getId(),
          rawSimpleStatus,
          model.getStatus()
        );
      }

      return true;
    }
    return false;
  }/**
   * 更新订单管理售后工单（带空值）
   * @param model 订单管理售后工单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(NavAfterSellOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    NavAfterSellOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("订单管理售后工单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(NavAfterSellOrder::getOrderId, model.getOrderId())
      .set(NavAfterSellOrder::getShopInfo, model.getShopInfo())
      .set(NavAfterSellOrder::getSite, model.getSite())
      .set(NavAfterSellOrder::getType, model.getType())
      .set(NavAfterSellOrder::getReason, model.getReason())
      .set(NavAfterSellOrder::getSource, model.getSource())
      .set(NavAfterSellOrder::getTag, model.getTag())
      .set(NavAfterSellOrder::getCut, model.getCut())
      .set(NavAfterSellOrder::getRefundStatus, model.getRefundStatus())
      .set(NavAfterSellOrder::getWay, model.getWay())
      .set(NavAfterSellOrder::getStatus, model.getStatus())
      .set(NavAfterSellOrder::getStatusExplain, model.getStatusExplain())
      .set(NavAfterSellOrder::getLastUpdateTime, model.getLastUpdateTime())
      .set(NavAfterSellOrder::getLastUpdateUser, model.getLastUpdateUser())
      .set(
        NavAfterSellOrder::getDeliveryWaybillId,
        model.getDeliveryWaybillId()
      )
      .set(NavAfterSellOrder::getBuyerName, model.getBuyerName())
      .set(NavAfterSellOrder::getBuyerEmail, model.getBuyerEmail())
      .set(
        NavAfterSellOrder::getDeliveryLogistics,
        model.getDeliveryLogistics()
      )
      .set(
        NavAfterSellOrder::getDeliveryRealFreight,
        model.getDeliveryRealFreight()
      )
      .set(NavAfterSellOrder::getDeliveryTrackId, model.getDeliveryTrackId())
      .set(NavAfterSellOrder::getDeliveryReceipt, model.getDeliveryReceipt())
      .set(NavAfterSellOrder::getDeliveryZipCode, model.getDeliveryZipCode())
      .set(NavAfterSellOrder::getDeliveryPhone, model.getDeliveryPhone())
      .set(NavAfterSellOrder::getDeliveryCountry, model.getDeliveryCountry())
      .set(NavAfterSellOrder::getDeliveryProvince, model.getDeliveryProvince())
      .set(NavAfterSellOrder::getDeliveryCity, model.getDeliveryCity())
      .set(NavAfterSellOrder::getDeliveryArea, model.getDeliveryArea())
      .set(
        NavAfterSellOrder::getDeliveryHouseNumber,
        model.getDeliveryHouseNumber()
      )
      .set(NavAfterSellOrder::getDeliveryCompany, model.getDeliveryCompany())
      .set(
        NavAfterSellOrder::getDeliveryAddressType,
        model.getDeliveryAddressType()
      )
      .set(NavAfterSellOrder::getDeliveryAddress1, model.getDeliveryAddress1())
      .set(NavAfterSellOrder::getDeliveryAddress2, model.getDeliveryAddress2())
      .set(NavAfterSellOrder::getDeliveryAddress3, model.getDeliveryAddress3())
      .set(
        NavAfterSellOrder::getDeliveryWarehouse,
        model.getDeliveryWarehouse()
      )
      .set(
        NavAfterSellOrder::getDeliveryLogisticsChannel,
        model.getDeliveryLogisticsChannel()
      )
      .set(NavAfterSellOrder::getRemark, model.getRemark())
      .set(NavAfterSellOrder::getTotalAmount, model.getTotalAmount())
      .set(NavAfterSellOrder::getThisAmount, model.getThisAmount())
      .set(NavAfterSellOrder::getRefundAmount, model.getRefundAmount())
      .eq(NavAfterSellOrder::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      // 更新简单状态流程
      if (model.getStatus() != null) {
        simpleStatusService.afterUpdate(
          "NavAfterSellOrder",
          currentUser == null ? "" : currentUser.getDisplayName(),
          entity.getId(),
          entity.getStatus(),
          model.getStatus()
        );
      }
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    NavAfterSellOrderSearchParamPo search
  ) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 售后信息(detail) 对应的对象
    NavAfterSellOrderDetailSearchParamPo detailSearchParam =
      new NavAfterSellOrderDetailSearchParamPo();
    detailSearchParam.setDisableDataPremissions(true);
    detailSearchParam.setParentNavAfterSellOrderInList(ids);
    NavAfterSellOrderDetailMapper localNavAfterSellOrderDetailMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(NavAfterSellOrderDetailMapper.class);
    detailSearchParam.applySqlSegments();
    List<Long> detailIdList = localNavAfterSellOrderDetailMapper.searchIds(
      detailSearchParam
    );
    if (!detailIdList.isEmpty()) {
      NavAfterSellOrderDetailService localNavAfterSellOrderDetailService =
        ContextHolder
          .getApplicationContext()
          .getBean(NavAfterSellOrderDetailService.class);
      localNavAfterSellOrderDetailService.batchDelete(detailIdList);
    }
  }

  /**
   * 删除订单管理售后工单
   * @param id 订单管理售后工单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除订单管理售后工单
   * @param ids 订单管理售后工单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<NavAfterSellOrderImportPo> excelToImportRow(
    NavAfterSellOrderImportPo row,
    Integer rowNumber,
    NavAfterSellOrderVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<NavAfterSellOrderImportPo> ir =
      new ImportRow<NavAfterSellOrderImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<NavAfterSellOrderImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new NavAfterSellOrderVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, NavAfterSellOrderImportPo.class);

    // 一般数据处理
    vo.setNavSellOrderId(SheetUtils.tryToLong(row.getNavSellOrderId()));
    if (StringUtils.hasText(row.getType())) {
      List<SysDictAllItem> typeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "type",
          n -> sysDictService.getDictItems("SCM00156")
        );
      NavAfterSellOrderVo finalVo = vo;
      typeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setType(i.getItemValue()),
          () ->
            ir.addError(
              "type",
              String.format(
                "必须为 %s 中之一",
                typeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getReason())) {
      List<SysDictAllItem> reasonItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "reason",
          n -> sysDictService.getDictItems("SCM00157")
        );
      NavAfterSellOrderVo finalVo = vo;
      reasonItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getReason()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setReason(i.getItemValue()),
          () ->
            ir.addError(
              "reason",
              String.format(
                "必须为 %s 中之一",
                reasonItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getSource())) {
      List<SysDictAllItem> sourceItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "source",
          n -> sysDictService.getDictItems("SCM00121")
        );
      NavAfterSellOrderVo finalVo = vo;
      sourceItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getSource()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setSource(i.getItemValue()),
          () ->
            ir.addError(
              "source",
              String.format(
                "必须为 %s 中之一",
                sourceItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getTag())) {
      List<SysDictAllItem> tagItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "tag",
          n -> sysDictService.getDictItems("SCM00175")
        );
      NavAfterSellOrderVo finalVo = vo;
      tagItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getTag()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setTag(i.getItemValue()),
          () ->
            ir.addError(
              "tag",
              String.format(
                "必须为 %s 中之一",
                tagItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getCut())) {
      List<SysDictAllItem> cutItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "cut",
          n -> sysDictService.getDictItems("SCM00158")
        );
      NavAfterSellOrderVo finalVo = vo;
      cutItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCut()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCut(i.getItemValue()),
          () ->
            ir.addError(
              "cut",
              String.format(
                "必须为 %s 中之一",
                cutItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getRefundStatus())) {
      List<SysDictAllItem> refundStatusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "refundStatus",
          n -> sysDictService.getDictItems("SCM00182")
        );
      NavAfterSellOrderVo finalVo = vo;
      refundStatusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getRefundStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setRefundStatus(i.getItemValue()),
          () ->
            ir.addError(
              "refundStatus",
              String.format(
                "必须为 %s 中之一",
                refundStatusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getWay())) {
      List<SysDictAllItem> wayItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "way",
          n -> sysDictService.getDictItems("SCM00159")
        );
      NavAfterSellOrderVo finalVo = vo;
      wayItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getWay()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setWay(i.getItemValue()),
          () ->
            ir.addError(
              "way",
              String.format(
                "必须为 %s 中之一",
                wayItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getStatus())) {
      List<SysDictAllItem> statusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "status",
          n -> sysDictService.getDictItems("SCM00176")
        );
      NavAfterSellOrderVo finalVo = vo;
      statusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatus(i.getItemValue()),
          () ->
            ir.addError(
              "status",
              String.format(
                "必须为 %s 中之一",
                statusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setDeliveryRealFreight(
      SheetUtils.tryToDecimal(row.getDeliveryRealFreight())
    );
    if (StringUtils.hasText(row.getDeliveryAddressType())) {
      List<SysDictAllItem> deliveryAddressTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "deliveryAddressType",
          n -> sysDictService.getDictItems("SCM00124")
        );
      NavAfterSellOrderVo finalVo = vo;
      deliveryAddressTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getDeliveryAddressType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setDeliveryAddressType(i.getItemValue()),
          () ->
            ir.addError(
              "deliveryAddressType",
              String.format(
                "必须为 %s 中之一",
                deliveryAddressTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setTotalAmount(SheetUtils.tryToDecimal(row.getTotalAmount()));
    vo.setThisAmount(SheetUtils.tryToDecimal(row.getThisAmount()));
    vo.setRefundAmount(SheetUtils.tryToDecimal(row.getRefundAmount()));
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getShopInfoShopName()) &&
      SheetUtils.isBlank(row.getShopInfo())
    ) {
      ShopInfoSearchParamPo shopInfoSearchParam = new ShopInfoSearchParamPo();
      shopInfoSearchParam.setLimit(2); // 最大只返回二行记录
      shopInfoSearchParam.setShopNameEq(
        SheetUtils.trim(row.getShopInfoShopName())
      );
      shopInfoSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopInfoMatches = shopInfoMapper.search(
        shopInfoSearchParam
      );
      if (shopInfoMatches.size() == 0) {
        ir.addError("shopInfoShopName", "未能在店铺中找到匹配的数据");
      } else if (shopInfoMatches.size() > 1) {
        ir.addError(
          "shopInfoShopName",
          "关联不唯一，在店铺中找到多个匹配的数据"
        );
      } else {
        vo.setShopInfo(shopInfoMatches.get(0).getId());
      }
    }
    // 处理关联字段“站点”
    if (
      !SheetUtils.isBlank(row.getSiteName()) &&
      SheetUtils.isBlank(row.getSite())
    ) {
      SysRegionSearchParamPo siteSearchParam = new SysRegionSearchParamPo();
      siteSearchParam.setLimit(2); // 最大只返回二行记录
      siteSearchParam.setNameEq(SheetUtils.trim(row.getSiteName()));
      siteSearchParam.applySqlSegments();
      List<SysRegionItemVo> siteMatches = sysRegionMapper.search(
        siteSearchParam
      );
      if (siteMatches.size() == 0) {
        ir.addError("siteName", "未能在站点中找到匹配的数据");
      } else if (siteMatches.size() > 1) {
        ir.addError("siteName", "关联不唯一，在站点中找到多个匹配的数据");
      } else {
        vo.setSite(siteMatches.get(0).getId());
      }
    }
    // 处理关联字段“客选物流”
    if (
      !SheetUtils.isBlank(row.getDeliveryLogisticsLabel()) &&
      SheetUtils.isBlank(row.getDeliveryLogistics())
    ) {
      NavLogisticsProviderViewSearchParamPo deliveryLogisticsSearchParam =
        new NavLogisticsProviderViewSearchParamPo();
      deliveryLogisticsSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryLogisticsSearchParam.setLabelEq(
        SheetUtils.trim(row.getDeliveryLogisticsLabel())
      );
      deliveryLogisticsSearchParam.applySqlSegments();
      List<NavLogisticsProviderViewItemVo> deliveryLogisticsMatches =
        navLogisticsProviderViewMapper.search(deliveryLogisticsSearchParam);
      if (deliveryLogisticsMatches.size() == 0) {
        ir.addError(
          "deliveryLogisticsLabel",
          "未能在物流管理-客选物流-视图中找到匹配的数据"
        );
      } else if (deliveryLogisticsMatches.size() > 1) {
        ir.addError(
          "deliveryLogisticsLabel",
          "关联不唯一，在物流管理-客选物流-视图中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryLogistics(deliveryLogisticsMatches.get(0).getId());
      }
    }
    // 处理关联字段“国家/地区”
    if (
      !SheetUtils.isBlank(row.getDeliveryCountryCountry()) &&
      SheetUtils.isBlank(row.getDeliveryCountry())
    ) {
      SysCountrySearchParamPo deliveryCountrySearchParam =
        new SysCountrySearchParamPo();
      deliveryCountrySearchParam.setLimit(2); // 最大只返回二行记录
      deliveryCountrySearchParam.setCountryEq(
        SheetUtils.trim(row.getDeliveryCountryCountry())
      );
      deliveryCountrySearchParam.applySqlSegments();
      List<SysCountryItemVo> deliveryCountryMatches = sysCountryMapper.search(
        deliveryCountrySearchParam
      );
      if (deliveryCountryMatches.size() == 0) {
        ir.addError("deliveryCountryCountry", "未能在国家中找到匹配的数据");
      } else if (deliveryCountryMatches.size() > 1) {
        ir.addError(
          "deliveryCountryCountry",
          "关联不唯一，在国家中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryCountry(deliveryCountryMatches.get(0).getId());
      }
    }
    // 处理关联字段“发货仓库”
    if (
      !SheetUtils.isBlank(row.getDeliveryWarehouseName()) &&
      SheetUtils.isBlank(row.getDeliveryWarehouse())
    ) {
      WarehouseSearchParamPo deliveryWarehouseSearchParam =
        new WarehouseSearchParamPo();
      deliveryWarehouseSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryWarehouseSearchParam.setNameEq(
        SheetUtils.trim(row.getDeliveryWarehouseName())
      );
      deliveryWarehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> deliveryWarehouseMatches = warehouseMapper.search(
        deliveryWarehouseSearchParam
      );
      if (deliveryWarehouseMatches.size() == 0) {
        ir.addError(
          "deliveryWarehouseName",
          "未能在仓库即时库存中找到匹配的数据"
        );
      } else if (deliveryWarehouseMatches.size() > 1) {
        ir.addError(
          "deliveryWarehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryWarehouse(deliveryWarehouseMatches.get(0).getId());
      }
    }
    // 处理关联字段“物流方式”
    if (
      !SheetUtils.isBlank(row.getDeliveryLogisticsChannelLabel()) &&
      SheetUtils.isBlank(row.getDeliveryLogisticsChannel())
    ) {
      NavLogisticsChannelViewSearchParamPo deliveryLogisticsChannelSearchParam =
        new NavLogisticsChannelViewSearchParamPo();
      deliveryLogisticsChannelSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryLogisticsChannelSearchParam.setLabelEq(
        SheetUtils.trim(row.getDeliveryLogisticsChannelLabel())
      );
      deliveryLogisticsChannelSearchParam.applySqlSegments();
      List<NavLogisticsChannelViewItemVo> deliveryLogisticsChannelMatches =
        navLogisticsChannelViewMapper.search(
          deliveryLogisticsChannelSearchParam
        );
      if (deliveryLogisticsChannelMatches.size() == 0) {
        ir.addError(
          "deliveryLogisticsChannelLabel",
          "未能在物流管理-渠道基本信息-视图中找到匹配的数据"
        );
      } else if (deliveryLogisticsChannelMatches.size() > 1) {
        ir.addError(
          "deliveryLogisticsChannelLabel",
          "关联不唯一，在物流管理-渠道基本信息-视图中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryLogisticsChannel(
          deliveryLogisticsChannelMatches.get(0).getId()
        );
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<NavAfterSellOrderImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<NavAfterSellOrderImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            NavAfterSellOrderImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              NavAfterSellOrderImportPo row,
              AnalysisContext cxt
            ) {
              NavAfterSellOrderVo vo = new NavAfterSellOrderVo();
              ImportRow<NavAfterSellOrderImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<NavAfterSellOrderImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<NavAfterSellOrderImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      NavAfterSellOrderVo vo = new NavAfterSellOrderVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"售后单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "afterId".equals(m.getField())
          )
      ) {
        vo.setAfterId(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "NavAfterSellOrder.afterId")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    NavAfterSellOrderSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "shopInfo",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((NavAfterSellOrderItemVo) r).getShopInfoShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "site",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((NavAfterSellOrderItemVo) r).getSiteName())
          )
      );
      exportOptions.addFieldMappingOption(
        "type",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00156")
      );
      exportOptions.addFieldMappingOption(
        "source",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00121")
      );
      exportOptions.addFieldMappingOption(
        "tag",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00175")
      );
      exportOptions.addFieldMappingOption(
        "refundStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00182")
      );
      exportOptions.addFieldMappingOption(
        "way",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00159")
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00176")
      );
      exportOptions.addFieldMappingOption(
        "deliveryLogistics",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((NavAfterSellOrderItemVo) r).getDeliveryLogisticsLabel()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "deliveryCountry",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((NavAfterSellOrderItemVo) r).getDeliveryCountryCountry()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "deliveryAddressType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00124")
      );
      exportOptions.addFieldMappingOption(
        "deliveryWarehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((NavAfterSellOrderItemVo) r).getDeliveryWarehouseName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "deliveryLogisticsChannel",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((NavAfterSellOrderItemVo) r).getDeliveryLogisticsChannelLabel()
            )
          )
      );
      exportOptions.addStringFields(
        "afterId",
        "orderId",
        "shopInfoShopName",
        "siteName",
        "type",
        "source",
        "tag",
        "refundStatus",
        "way",
        "status",
        "statusExplain",
        "deliveryWaybillId",
        "buyerName",
        "buyerEmail",
        "deliveryLogisticsLabel",
        "deliveryTrackId",
        "deliveryReceipt",
        "deliveryZipCode",
        "deliveryPhone",
        "deliveryCountryCountry",
        "deliveryProvince",
        "deliveryCity",
        "deliveryArea",
        "deliveryHouseNumber",
        "deliveryCompany",
        "deliveryAddressType",
        "deliveryAddress1",
        "deliveryAddress2",
        "deliveryAddress3",
        "deliveryWarehouseName",
        "deliveryLogisticsChannelLabel",
        "remark"
      );

      String fileName = String.format(
        "订单管理售后工单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> typeItems = sysDictService.getDictItems("SCM00156");
    List<SysDictAllItem> sourceItems = sysDictService.getDictItems("SCM00121");
    List<SysDictAllItem> tagItems = sysDictService.getDictItems("SCM00175");
    List<SysDictAllItem> refundStatusItems = sysDictService.getDictItems(
      "SCM00182"
    );
    List<SysDictAllItem> wayItems = sysDictService.getDictItems("SCM00159");
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00176");
    List<SysDictAllItem> deliveryAddressTypeItems = sysDictService.getDictItems(
      "SCM00124"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<NavAfterSellOrderExcelPo> items =
      new ArrayList<NavAfterSellOrderExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<NavAfterSellOrderItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<NavAfterSellOrderItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (NavAfterSellOrderItemVo item : list) {
        NavAfterSellOrderExcelPo excel = new NavAfterSellOrderExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getType() != null) {
          typeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getType()))
            .findFirst()
            .ifPresent(i -> excel.setType(i.getItemText()));
        }
        if (item.getSource() != null) {
          sourceItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getSource()))
            .findFirst()
            .ifPresent(i -> excel.setSource(i.getItemText()));
        }
        if (item.getTag() != null) {
          tagItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getTag()))
            .findFirst()
            .ifPresent(i -> excel.setTag(i.getItemText()));
        }
        if (item.getRefundStatus() != null) {
          refundStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getRefundStatus()))
            .findFirst()
            .ifPresent(i -> excel.setRefundStatus(i.getItemText()));
        }
        if (item.getWay() != null) {
          wayItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getWay()))
            .findFirst()
            .ifPresent(i -> excel.setWay(i.getItemText()));
        }
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }
        if (item.getDeliveryAddressType() != null) {
          deliveryAddressTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getDeliveryAddressType()))
            .findFirst()
            .ifPresent(i -> excel.setDeliveryAddressType(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "订单管理售后工单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(NavAfterSellOrderExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过售后单号查询订单管理售后工单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByAfterId(String afterId) {
    return this.baseMapper.getIdByAfterId(afterId);
  }

  /**
   * 通过售后单号查询订单管理售后工单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByAfterId(List<String> list) {
    return this.baseMapper.getIdsByAfterId(list);
  }

  /**
   * 通过订单管理售后工单主键查询售后单号
   */
  @Override
  public String getAfterIdById(Long id) {
    return this.baseMapper.getAfterIdById(id);
  }

  /**
   * 通过订单管理售后工单主键查询售后单号列表
   */
  @Override
  public List<String> getAfterIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getAfterIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("afterId"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 订单管理售后工单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public NavAfterSellOrderVo getVoById(Long id) throws Exception {
    NavAfterSellOrderVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    NavAfterSellOrderDetailSearchParamPo detailSearchParamPo =
      new NavAfterSellOrderDetailSearchParamPo();
    detailSearchParamPo.setParentNavAfterSellOrder(id);
    detailSearchParamPo.getExtendData().put("queryMode", "sub");
    detailSearchParamPo.getExtendData().put("queryParent", "NavAfterSellOrder");
    detailSearchParamPo.applySqlSegments();
    vo.setDetail(navAfterSellOrderDetailService.search(detailSearchParamPo));

    NavSellOrderPlatformSearchParamPo platformSearchParamPo =
      new NavSellOrderPlatformSearchParamPo();
    platformSearchParamPo.setParentNavSellOrderEq(vo.getNavSellOrderId());
    platformSearchParamPo.applySqlSegments();
    platformSearchParamPo.getExtendData().put("queryMode", "sub");
    platformSearchParamPo
      .getExtendData()
      .put("queryParent", "NavAfterSellOrder");
    vo.setPlatform(navSellOrderPlatformService.search(platformSearchParamPo));

    NavSellOrderTransactionSearchParamPo transactionSearchParamPo =
      new NavSellOrderTransactionSearchParamPo();
    transactionSearchParamPo.setParentNavSellOrderEq(vo.getNavSellOrderId());
    transactionSearchParamPo.applySqlSegments();
    transactionSearchParamPo.getExtendData().put("queryMode", "sub");
    transactionSearchParamPo
      .getExtendData()
      .put("queryParent", "NavAfterSellOrder");
    vo.setTransaction(
      navSellOrderTransactionService.search(transactionSearchParamPo)
    );

    NavSellOrderDetailSearchParamPo productSearchParamPo =
      new NavSellOrderDetailSearchParamPo();
    productSearchParamPo.setParentNavSellOrderEq(vo.getNavSellOrderId());
    productSearchParamPo.applySqlSegments();
    productSearchParamPo.getExtendData().put("queryMode", "sub");
    productSearchParamPo
      .getExtendData()
      .put("queryParent", "NavAfterSellOrder");
    vo.setProduct(navSellOrderDetailService.search(productSearchParamPo));

    NavSellOrderDeclareSearchParamPo declareSearchParamPo =
      new NavSellOrderDeclareSearchParamPo();
    declareSearchParamPo.setParentNavSellOrderEq(vo.getNavSellOrderId());
    declareSearchParamPo.applySqlSegments();
    declareSearchParamPo.getExtendData().put("queryMode", "sub");
    declareSearchParamPo
      .getExtendData()
      .put("queryParent", "NavAfterSellOrder");
    vo.setDeclare(navSellOrderDeclareService.search(declareSearchParamPo));

    return vo;
  }

  /**
   * 分页查询订单管理售后工单
   * @param search 查询条件
   * @return 订单管理售后工单分页查询结果
   */
  @Override
  public Page<NavAfterSellOrderItemVo> pageSearch(
    NavAfterSellOrderSearchParamPo search
  ) {
    Page<NavAfterSellOrderItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(NavAfterSellOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 订单管理售后工单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'NavAfterSellOrderOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<NavAfterSellOrderItemVo>> searchOptions(
    NavAfterSellOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询订单管理售后工单
   * @param search 查询条件
   * @return 订单管理售后工单列表查询结果
   */
  @Override
  public List<NavAfterSellOrderItemVo> search(
    NavAfterSellOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询订单管理售后工单最后更新时间
   * @param search 查询条件
   * @return 订单管理售后工单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(NavAfterSellOrderSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Override
  public void submit(List<Long> ids) throws Exception {
    if (navAfterSellOrderSubmitAction == null) {
      throw new Exception("此操作当前不可用");
    }
    navAfterSellOrderSubmitAction.run(ids);
  }

  /**
   * 审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了审核操作"
  )
  @Override
  public void process(List<Long> ids) throws Exception {
    if (navAfterSellOrderProcessAction == null) {
      throw new Exception("此操作当前不可用");
    }
    navAfterSellOrderProcessAction.run(ids);
  }

  /**
   * 作废
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了作废操作"
  )
  @Override
  public void cancel(List<Long> ids) throws Exception {
    if (navAfterSellOrderCancelAction == null) {
      throw new Exception("此操作当前不可用");
    }
    navAfterSellOrderCancelAction.run(ids);
  }

  /**
   * 标记退款
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了标记退款操作"
  )
  @Override
  public void issuRefund(List<Long> ids) throws Exception {
    if (navAfterSellOrderIssuRefundAction == null) {
      throw new Exception("此操作当前不可用");
    }
    navAfterSellOrderIssuRefundAction.run(ids);
  }

  /**
   * 标记补货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了标记补货操作"
  )
  @Override
  public void issuReturn(List<Long> ids) throws Exception {
    if (navAfterSellOrderIssuReturnAction == null) {
      throw new Exception("此操作当前不可用");
    }
    navAfterSellOrderIssuReturnAction.run(ids);
  }

  /**
   * 扣库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了扣库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void subInventory(Long id) throws Exception {
    NavAfterSellOrderVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareSubInventory(vo);
    inventoryBusinessService.outbound(formVo);
  }

  /**
   * 准备用于 扣库存 的参数
   */
  protected InventoryOutboundFormVo prepareSubInventory(NavAfterSellOrderVo vo)
    throws Exception {
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(NavAfterSellOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderId());
    formVo.setDocumentType("售后订单");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getDeliveryWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (NavAfterSellOrderDetailItemVo navAfterSellOrderDetail : vo.getDetail()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(navAfterSellOrderDetail.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String
            .valueOf(navAfterSellOrderDetail.getAfterQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(navAfterSellOrderDetail.getAfterQuantity())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        null,
        Integer.parseInt(
          String
              .valueOf(navAfterSellOrderDetail.getAfterQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(navAfterSellOrderDetail.getAfterQuantity())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(navAfterSellOrderDetail.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 加库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了加库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void addInventory(Long id) throws Exception {
    NavAfterSellOrderVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareAddInventory(vo);
    inventoryBusinessService.outbound(formVo);
  }

  /**
   * 准备用于 加库存 的参数
   */
  protected InventoryOutboundFormVo prepareAddInventory(NavAfterSellOrderVo vo)
    throws Exception {
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(NavAfterSellOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消出库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderId());
    formVo.setDocumentType("售后订单");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getDeliveryWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (NavAfterSellOrderDetailItemVo navAfterSellOrderDetail : vo.getDetail()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(navAfterSellOrderDetail.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String
            .valueOf(navAfterSellOrderDetail.getAfterQuantity())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(navAfterSellOrderDetail.getAfterQuantity())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        null,
        Integer.parseInt(
          String
              .valueOf(navAfterSellOrderDetail.getAfterQuantity())
              .equals("null")
            ? "0"
            : String.valueOf(navAfterSellOrderDetail.getAfterQuantity())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(navAfterSellOrderDetail.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    NavAfterSellOrderSearchParamPo search =
      new NavAfterSellOrderSearchParamPo();
    return MapUtil
      .builder()
      .put("AllAfterOrder", this.baseMapper.allAfterOrderCount(search))
      .put("PendingAfterOrder", this.baseMapper.pendingAfterOrderCount(search))
      .put(
        "PendingAuditAfterOrder",
        this.baseMapper.pendingAuditAfterOrderCount(search)
      )
      .put(
        "ProcessingAfterOrder",
        this.baseMapper.processingAfterOrderCount(search)
      )
      .put(
        "CompletedAfterOrder",
        this.baseMapper.completedAfterOrderCount(search)
      )
      .put("CancelAfterOrder", this.baseMapper.cancelAfterOrderCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<NavAfterSellOrderItemVo> allAfterOrder(
    NavAfterSellOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allAfterOrder(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<NavAfterSellOrderItemVo> allAfterOrderPage(
    NavAfterSellOrderSearchParamPo search
  ) {
    Page<NavAfterSellOrderItemVo> allAfterOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allAfterOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allAfterOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allAfterOrderPage =
      this.baseMapper.allAfterOrderPage(
          search.toPage(this.baseMapper.allAfterOrderCount(search)),
          search
        );
    List<Long> recordIds = allAfterOrderPage
      .getRecords()
      .stream()
      .map(NavAfterSellOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allAfterOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allAfterOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allAfterOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allAfterOrderPage;
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allAfterOrderLastUpdateTime(
    NavAfterSellOrderSearchParamPo search
  ) {
    return this.baseMapper.allAfterOrderLastUpdateTime(search);
  }

  /**
   * 待提交
   */
  @Override
  public List<NavAfterSellOrderItemVo> pendingAfterOrder(
    NavAfterSellOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.pendingAfterOrder(search);
  }

  /**
   * 待提交分页
   */
  @Override
  public Page<NavAfterSellOrderItemVo> pendingAfterOrderPage(
    NavAfterSellOrderSearchParamPo search
  ) {
    Page<NavAfterSellOrderItemVo> pendingAfterOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return pendingAfterOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return pendingAfterOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    pendingAfterOrderPage =
      this.baseMapper.pendingAfterOrderPage(
          search.toPage(this.baseMapper.pendingAfterOrderCount(search)),
          search
        );
    List<Long> recordIds = pendingAfterOrderPage
      .getRecords()
      .stream()
      .map(NavAfterSellOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return pendingAfterOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return pendingAfterOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    pendingAfterOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return pendingAfterOrderPage;
  }

  /**
   * 查询待提交最后更新时间
   * @param search 查询条件
   * @return 待提交最后更新时间
   */
  @Override
  public Date pendingAfterOrderLastUpdateTime(
    NavAfterSellOrderSearchParamPo search
  ) {
    return this.baseMapper.pendingAfterOrderLastUpdateTime(search);
  }

  /**
   * 待审批
   */
  @Override
  public List<NavAfterSellOrderItemVo> pendingAuditAfterOrder(
    NavAfterSellOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.pendingAuditAfterOrder(search);
  }

  /**
   * 待审批分页
   */
  @Override
  public Page<NavAfterSellOrderItemVo> pendingAuditAfterOrderPage(
    NavAfterSellOrderSearchParamPo search
  ) {
    Page<NavAfterSellOrderItemVo> pendingAuditAfterOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return pendingAuditAfterOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return pendingAuditAfterOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    pendingAuditAfterOrderPage =
      this.baseMapper.pendingAuditAfterOrderPage(
          search.toPage(this.baseMapper.pendingAuditAfterOrderCount(search)),
          search
        );
    List<Long> recordIds = pendingAuditAfterOrderPage
      .getRecords()
      .stream()
      .map(NavAfterSellOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return pendingAuditAfterOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return pendingAuditAfterOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    pendingAuditAfterOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return pendingAuditAfterOrderPage;
  }

  /**
   * 查询待审批最后更新时间
   * @param search 查询条件
   * @return 待审批最后更新时间
   */
  @Override
  public Date pendingAuditAfterOrderLastUpdateTime(
    NavAfterSellOrderSearchParamPo search
  ) {
    return this.baseMapper.pendingAuditAfterOrderLastUpdateTime(search);
  }

  /**
   * 处理中
   */
  @Override
  public List<NavAfterSellOrderItemVo> processingAfterOrder(
    NavAfterSellOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.processingAfterOrder(search);
  }

  /**
   * 处理中分页
   */
  @Override
  public Page<NavAfterSellOrderItemVo> processingAfterOrderPage(
    NavAfterSellOrderSearchParamPo search
  ) {
    Page<NavAfterSellOrderItemVo> processingAfterOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return processingAfterOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return processingAfterOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    processingAfterOrderPage =
      this.baseMapper.processingAfterOrderPage(
          search.toPage(this.baseMapper.processingAfterOrderCount(search)),
          search
        );
    List<Long> recordIds = processingAfterOrderPage
      .getRecords()
      .stream()
      .map(NavAfterSellOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return processingAfterOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return processingAfterOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    processingAfterOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return processingAfterOrderPage;
  }

  /**
   * 查询处理中最后更新时间
   * @param search 查询条件
   * @return 处理中最后更新时间
   */
  @Override
  public Date processingAfterOrderLastUpdateTime(
    NavAfterSellOrderSearchParamPo search
  ) {
    return this.baseMapper.processingAfterOrderLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<NavAfterSellOrderItemVo> completedAfterOrder(
    NavAfterSellOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.completedAfterOrder(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<NavAfterSellOrderItemVo> completedAfterOrderPage(
    NavAfterSellOrderSearchParamPo search
  ) {
    Page<NavAfterSellOrderItemVo> completedAfterOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return completedAfterOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return completedAfterOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    completedAfterOrderPage =
      this.baseMapper.completedAfterOrderPage(
          search.toPage(this.baseMapper.completedAfterOrderCount(search)),
          search
        );
    List<Long> recordIds = completedAfterOrderPage
      .getRecords()
      .stream()
      .map(NavAfterSellOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return completedAfterOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return completedAfterOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    completedAfterOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return completedAfterOrderPage;
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date completedAfterOrderLastUpdateTime(
    NavAfterSellOrderSearchParamPo search
  ) {
    return this.baseMapper.completedAfterOrderLastUpdateTime(search);
  }

  /**
   * 已作废
   */
  @Override
  public List<NavAfterSellOrderItemVo> cancelAfterOrder(
    NavAfterSellOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.cancelAfterOrder(search);
  }

  /**
   * 已作废分页
   */
  @Override
  public Page<NavAfterSellOrderItemVo> cancelAfterOrderPage(
    NavAfterSellOrderSearchParamPo search
  ) {
    Page<NavAfterSellOrderItemVo> cancelAfterOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return cancelAfterOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return cancelAfterOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    cancelAfterOrderPage =
      this.baseMapper.cancelAfterOrderPage(
          search.toPage(this.baseMapper.cancelAfterOrderCount(search)),
          search
        );
    List<Long> recordIds = cancelAfterOrderPage
      .getRecords()
      .stream()
      .map(NavAfterSellOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return cancelAfterOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return cancelAfterOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    cancelAfterOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return cancelAfterOrderPage;
  }

  /**
   * 查询已作废最后更新时间
   * @param search 查询条件
   * @return 已作废最后更新时间
   */
  @Override
  public Date cancelAfterOrderLastUpdateTime(
    NavAfterSellOrderSearchParamPo search
  ) {
    return this.baseMapper.cancelAfterOrderLastUpdateTime(search);
  }
}
